package com.smitish.vueblog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smitish.vueblog.common.lang.Result;
import com.smitish.vueblog.entity.Message;
import com.smitish.vueblog.service.MessageService;
import com.smitish.vueblog.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Smitish
 * @since 2020-12-12
 */
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    MessageService messageService;

    /**
     * 通过token验证
     *
     * @param message 消息实体
     * @return 返回发送是否成功
     */
    @RequiresAuthentication
    @PostMapping("/post")
    public Result postMessage(@RequestBody Message message) {
        message.setFromUserId(ShiroUtil.getProfile().getId());
        boolean b = messageService.saveOrUpdate(message);
        if (b)
            return Result.success("发送成功");
        return Result.fail("发送失败");
    }

    /**
     * 获取 发送给某用户出去的 所有信息
     *
     * @param id 对方id
     * @return 所有信息
     */
    @RequiresAuthentication
    @GetMapping("/getMessage/{id}")
    public Result getMessage(@PathVariable(name = "id") Long id) {
        // 发起查询请求用户的id
        Long uid = ShiroUtil.getProfile().getId();
        // 发起查询请求对象的id : id
        List<Message> list = messageService.list(new QueryWrapper<Message>()
                .eq("from_user_id", uid)
                .eq("to_user_id", id)
                .orderByDesc("created_time"));
        return Result.success(list);
    }

    /**
     * 获取 发送给用户的消息 以及 用户发送过来的消息
     *
     * @param id          对方用户id
     * @param currentPage 当前页面
     * @return 返回分页信息
     */
    @RequiresAuthentication
    @GetMapping("/getChatMessage/{id}")
    public Result getChatMessage(@PathVariable(name = "id") Long id, @RequestParam(defaultValue = "1") Integer currentPage) {
        // 发起查询请求用户的id
        Long uid = ShiroUtil.getProfile().getId();
        // 每一页 十条数据
        Page page = new Page(currentPage, 10);
        IPage pages = messageService.page(page, new QueryWrapper<Message>()
                .orderByDesc("created_time").eq("from_user_id", uid).eq("to_user_id", id).or()
                .eq("from_user_id", id).eq("to_user_id", uid)
        );
        return Result.success(pages);
    }

}
